import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:ljy_flutter/riverpod/riverpod_next_page.dart';
import 'package:ljy_flutter/riverpod/riverpod_provider.dart';

class RiverpodHomeWidget extends StatelessWidget {
  const RiverpodHomeWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: RiverpodHomeScreen());
  }
}

class RiverpodHomeScreen extends ConsumerWidget {
  const RiverpodHomeScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final user = ref.watch(userProvider);
    final articles = ref.watch(articlesProvider);
    return Scaffold(
      appBar: AppBar(title: Text('Riverpod example')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            user == null
                ? Text('NO user logged in.')
                : Text('User: ${user.name}'),
            ElevatedButton(
              onPressed: () {
                ref.read(userProvider.notifier).updateUser('Alice xiandao');
              },
              child: Text('Login as Alice'),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () {
                ref.read(articlesProvider.notifier).fetchArticles();
              },
              child: Text('Load Articles'),
            ),
            articles.isEmpty
                ? CircularProgressIndicator()
                : Expanded(
                  child: ListView.builder(
                    itemCount: articles.length,
                    itemBuilder: (context, index) {
                      return ListTile(
                        title: Text(articles[index].title),
                        subtitle: Text(articles[index].content),
                      );
                    },
                  ),
                ),
            Consumer(
              builder: (context, ref, child) {
                final count = ref.watch(counterProvider);
                return Text('值值值$count');
              },
            ),
            ElevatedButton(
              onPressed: () {
                ref.read(counterProvider.notifier).state++;
              },
              child: Text('add click'),
            ),
            TextButton(
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) {
                      return RiverpodNextPage();
                    },
                  ),
                );
              },
              child: Text('下一页'),
            ),
          ],
        ),
      ),
    );
  }
}
